package com.icesoft.core.common.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

public class InetAddressUtils {

    public static InetAddress getLocalInetAddress() throws UnknownHostException {
        InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
        if (jdkSuppliedAddress.isSiteLocalAddress()) {
            return jdkSuppliedAddress;
        }
        try {
            InetAddress candidateAddress = null;
            for (InetAddress inetAddr : getLocalInetAddressSet()) {
                if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址127.0.0.1
                    if (inetAddr.isSiteLocalAddress()) {
                        // 如果是site-local地址，就是它了
                        return inetAddr;
                    } else if (candidateAddress == null) {
                        // site-local类型的地址未被发现，先记录候选地址
                        candidateAddress = inetAddr;
                    }
                }
            }
            if (candidateAddress != null) {
                return candidateAddress;
            }
        } catch (SocketException ignore) {
            //ignore
        }
        // 如果没有发现 non-loopback地址.只能用最次选的方案
        return jdkSuppliedAddress;
    }

    public static Set<InetAddress> getLocalInetAddressSet() throws SocketException {
        Set<InetAddress> inetAddressSet = new HashSet<>();
        // 遍历所有的网络接口
        for (Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
            NetworkInterface netInterface = ifaces.nextElement();
            if (netInterface.isVirtual() || !netInterface.isUp()) {
                continue;
            }
            // 在所有的接口下再遍历IP
            for (Enumeration<InetAddress> inetAddrs = netInterface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
                InetAddress inetAddress = inetAddrs.nextElement();
                inetAddressSet.add(inetAddress);

            }
        }
        return inetAddressSet;
    }
}
